/*
 * @Author: silence
 * @Date: 2023-03-14 15:34:20
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2023-10-31 09:14:24
 * @Description: 登录页
 */

import 'package:ems_neutral_app/base/SilTabbarPage.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sil_base_widget_package/combined_widget/toast/SilToast.dart';
import 'package:sil_utils_package/sil_utils_package.dart';

import '../../../api/ApiUtils.dart';
import '../../../api/request/CommonRequest.dart';
import '../../../api/request/UserRequest.dart';
import '../../../utils/router/ARouter.dart';
import '../../../utils/toast/SilToastExtends.dart';
import '../../Mine/Language/SilLocalizations/SilLocalizations.dart';

/// 登录方式
enum LoginMethod {
  LoginMethodByEmail, // 邮箱登录
  LoginMethodByPhone, // 手机号登录
  LoginMethodByPassword, // 密码登录
}

class LoginController extends GetxController {
  /// 是否遵守协议
  final isAllowedProtocal = false.obs;

  /// 设置遵守协议
  allowProtocalFunc(bool isAllow) {
    this.isAllowedProtocal.value = isAllow;
  }

  /// 注册
  register(
      {required BuildContext context,
      String? email,
      String? phone,
      String? code,
      String? password,
      String? confirmPassword,
      String? country,
      String? areaCode,
      bool phoneRegister = true,
      Function(dynamic)? successHandler}) {
    /// 去掉前后空格
    email = email?.trim();
    phone = phone?.trim();
    code = code?.trim();
    password = password?.trim();

    String? username;

    // 手机号注册
    if (phoneRegister) {
      username = phone;

      /// 验证手机号
      if (verifyPhoneHandler(context, phone) == false) return;
    } else {
      username = email;

      /// 验证邮箱
      if (verifyEmailHandler(context, email) == false) return;
    }

    /// 验证两次输入的密码是否一致
    if (verifyPasswordHandler(context, password) == false) return;
    if (SilTools.stringIsEmpty(confirmPassword)) {
      SilToastExtends.toastMsg(
          LangOf(context)?.common?.againPwd_notEmpty); // 再次输入密码不能为空
      return;
    }
    if (confirmPassword != password) {
      SilToastExtends.toastMsg(
          LangOf(context)?.common?.pwd_not_match); // 两次密码不一致
      return;
    }

    /// 验证验证码
    if (verifyCodeHandler(context, code) == false) return;

    /// 验证国家
    if (SilTools.stringIsEmpty(country) || SilTools.stringIsEmpty(areaCode)) {
      SilToastExtends.toastMsg(LangOf(context)?.common?.country_notEmpty);
      return false;
    }

    apiShow(context,
        api: api_user_register(
            username: username,
            code: code,
            password: password,
            country: country,
            areaCode: areaCode), success: (result) async {
      String? success = LangOf(context)?.common?.register_success;
      if (!SilTools.stringIsEmpty(success)) SilToast.show(success!);

      ARoute.replacePage(context, SilTabbar());
      if (successHandler != null) successHandler(result);
    });
  }

  /// 登录
  login(
      {required BuildContext context,
      String? phone,
      String? email,
      String? code,
      String? password,
      LoginMethod loginMethod = LoginMethod.LoginMethodByPhone,
      Function(dynamic)? successHandler}) {
    /// 去掉前后空格
    email = email?.trim();
    phone = phone?.trim();
    code = code?.trim();
    password = password?.trim();
    if (loginMethod == LoginMethod.LoginMethodByPassword) {
      /// 验证账号和密码
      if (verifyAccountHandler(context, email ?? phone) == false) return;
      if (verifyPasswordHandler(context, password) == false) return;
    } else {
      /// 验证手机号/邮箱
      if (loginMethod == LoginMethod.LoginMethodByPhone) {
        if (verifyPhoneHandler(context, phone) == false) return;
      } else {
        if (verifyEmailHandler(context, email) == false) return;
      }

      /// 验证验证码
      if (verifyCodeHandler(context, code) == false) return;
    }

    apiShow(context,
        api: api_user_login(
            phone: phone,
            email: email,
            code: code,
            password: password), success: (result) async {
      /// 登录成功
      SilToastExtends.toastMsg(LangOf(context)?.common?.login_success);
      ARoute.replacePage(context, SilTabbar());
      if (successHandler != null) successHandler(result);
    });
  }

  /// 验证忘记密码
  verifyForgetPwd(
      {required BuildContext context,
      String? phone,
      String? email,
      String? code,
      bool choosePhoneBack = false,
      Function()? successHandler}) {
    /// 去掉前后空格
    email = email?.trim();
    phone = phone?.trim();
    code = code?.trim();

    /// 手机号找回
    if (choosePhoneBack) {
      if (verifyPhoneHandler(context, phone) == false) return;
    } else {
      /// 密码找回
      if (verifyEmailHandler(context, email) == false) return;
    }

    /// 验证验证码
    if (verifyCodeHandler(context, code) == false) return;
    if (successHandler != null) successHandler();
  }

  /// 更新/设置登录密码
  updatePassword(
      {required BuildContext context,
      Function(dynamic)? successHandler,
      String? account,
      String? code,
      String? password,
      String? confirmPassword}) {
    /// 去掉前后空格
    account = account?.trim();
    code = code?.trim();
    password = password?.trim();

    /// 验证两次输入的密码是否一致
    if (verifyPasswordHandler(context, password) == false) return;
    if (SilTools.stringIsEmpty(confirmPassword)) {
      SilToastExtends.toastMsg(
          LangOf(context)?.common?.againPwd_notEmpty); // 再次输入密码不能为空
      return;
    }
    if (confirmPassword != password) {
      SilToastExtends.toastMsg(
          LangOf(context)?.common?.pwd_not_match); // 两次密码不一致
      return;
    }

    /// 验证账号
    if (verifyAccountHandler(context, account) == false) return;

    /// 验证验证码
    if (verifyCodeHandler(context, code) == false) return;

    /// 判断当前账号是邮箱，还是手机号
    String? phone, email;
    if (account?.email() == true) {
      email = account;
    } else {
      phone = account;
    }

    apiShow(context,
        api: api_user_set_password(
            phone: phone,
            email: email,
            code: code,
            password: password!), success: (result) {
      // 密码设置成功
      SilToastExtends.toastMsg(LangOf(context)?.common?.edit_success);
      if (successHandler != null) successHandler(result);
    });
  }

  /// 请求发送验证码
  requestSendCode(
      {required BuildContext context,
      Function(dynamic)? successHandler,
      String? account}) {
    /// 去除前后空格
    account = account?.trim();
    if (verifyAccountHandler(context, account) == false) return;

    String? phone, email;
    // 判断当前账号是邮箱，还是手机号
    if (account?.email() == true) {
      email = account;
    } else {
      phone = account;
    }

    apiShow(context, api: api_send_code(email: email, phone: phone),
        success: (result) {
      // 验证码发送成功
      SilToastExtends.toastMsg(LangOf(context)?.common?.codeSend);
      if (successHandler != null) successHandler(result);
    }, showLoading: true);
  }

  /// 验证账号
  bool verifyAccountHandler(BuildContext context, String? account) {
    if (SilTools.stringIsEmpty(account)) {
      SilToastExtends.toastMsg(LangOf(context)?.common?.account_notEmpty);
      return false;
    }

    /// 先验证手机号，再验证邮箱
    if (account?.isPhoneNumber == true) {
      if (verifyPhoneHandler(context, account) == false) return false;
    } else {
      if (verifyEmailHandler(context, account) == false) return false;
    }

    return true;
  }

  /// 验证手机号
  bool verifyPhoneHandler(BuildContext context, String? phone) {
    if (SilTools.stringIsEmpty(phone)) {
      SilToastExtends.toastMsg(LangOf(context)?.common?.phone_notEmpty);
      return false;
    }

    if (phone?.phoneNumber() == false) {
      SilToastExtends.toastMsg(LangOf(context)?.common?.phone_correctFormat);
      return false;
    }

    return true;
  }

  /// 验证邮箱
  bool verifyEmailHandler(BuildContext context, String? email) {
    if (SilTools.stringIsEmpty(email)) {
      SilToastExtends.toastMsg(LangOf(context)?.common?.email_notEmpty);
      return false;
    }

    if (email?.email() == false) {
      SilToastExtends.toastMsg(LangOf(context)?.common?.email_correctFormat);
      return false;
    }

    return true;
  }

  /// 验证验证码
  bool verifyCodeHandler(BuildContext context, String? code) {
    if (SilTools.stringIsEmpty(code)) {
      SilToastExtends.toastMsg(LangOf(context)?.common?.code_notEmpty);
      return false;
    }

    if (code?.length != 6) {
      SilToastExtends.toastMsg(LangOf(context)?.common?.code_error);
      return false;
    }

    return true;
  }

  /// 验证密码
  bool verifyPasswordHandler(BuildContext context, String? password) {
    if (SilTools.stringIsEmpty(password)) {
      SilToastExtends.toastMsg(LangOf(context)?.common?.pwd_notEmpty);
      return false;
    }

    return true;
  }
}
